//
//  CpdEasemobCecPlugin.m
//  Runner
//
//  Created by 123456 on 2023/10/30.
//

#import "CpdEasemobCECPlugin.h"
#import <HelpDesk/HelpDesk.h>
#import <HyphenateChat/HyphenateChat.h>
#import "MessageManage.h"
#import "HxChatManage.h"

@implementation CpdEasemobCECPlugin


+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
    FlutterMethodChannel* channel = [FlutterMethodChannel
                                     methodChannelWithName:@"cpd_easemob_cec"
                                     binaryMessenger:[registrar messenger]];
    CpdEasemobCECPlugin* instance = [[CpdEasemobCECPlugin alloc] init];
    [[HxChatManage shared] registerWithRegistrar:registrar];
    [registrar addMethodCallDelegate:instance channel:channel];
}

- (void)handleMethodCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    if ([@"init" isEqualToString:call.method]) {
        
        [self initMethodWithCall:call result:result];
        
    } else if ([@"register" isEqualToString:call.method]) {
        
        [self registerMethodWithCall:call result:result];
        
    } else if ([@"login" isEqualToString:call.method]) {
        
        [self loginMethodWithCall:call result:result];
        
    } else if ([@"loginWithToken" isEqualToString:call.method]) {
        
        [self loginWithTokenMethodWithCall:call result:result];
        
    } else if ([@"isLoggedInBefore" isEqualToString:call.method]) {
        
        [self isLoginMethodWithCall:call result:result];
        
    } else if ([@"logout" isEqualToString:call.method]) {
        
        [self logoutMethodWithCall:call result:result];
        
    } else if ([@"sendTextMessage" isEqualToString:call.method]) {
        [self sendMessageWithCall:call result:result];
    } else if ([@"loadMessages" isEqualToString:call.method]) {
        
        [self loadMessagesWithCall:call result:result];
        
    } else if ([@"getAllMessage" isEqualToString:call.method]) {
        
        [self getAllMessageWithCall:call result:result];
        
    } else if ([@"unreadMessageCount" isEqualToString:call.method]) {
        
        [self unreadMessageCountWithCall:call result:result];
        
    } else if ([@"markAllMessageAsRead" isEqualToString:call.method]) {
        [self markAllMessageAsReadWithCall:call result:result];
    } else if ([@"sendEvalMessage" isEqualToString:call.method]) {
        [self sendEvalMessageWithCall:call result:result];
    } else {
        result(FlutterMethodNotImplemented);
    }
}


- (void)initMethodWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    HDOptions *option = [[HDOptions alloc] init];
    NSDictionary *args = (NSDictionary *)call.arguments;
    NSDictionary *arguments = args[@"args"];
    
    option.appkey = arguments[@"appKey"];
    option.tenantId = arguments[@"tenantId"];
    HDError *error = [[HDClient sharedClient] initializeSDKWithOptions:option];
    if (error != nil) {
        result([FlutterError errorWithCode:[NSString stringWithFormat:@"%@", @(error.code)] message:error.errorDescription details:nil]);
        return;
    }
    [[HxChatManage shared] setEventMessage];
    result(@(true));
}

- (void)registerMethodWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSDictionary *args = call.arguments;
    NSDictionary *arguments = args[@"args"];
    
    NSString *username = arguments[@"username"];
    NSString *password = arguments[@"password"];
    HDError *error = [[HDClient sharedClient] registerWithUsername:username password:password];
    if (error != nil) {
        result([FlutterError errorWithCode:[NSString stringWithFormat:@"%@", @(error.code)] message:error.errorDescription details:nil]);
        return;
    }
    result(@(true));
}

- (void)loginMethodWithCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSDictionary *args = call.arguments;
    NSDictionary *arguments = args[@"args"];

    NSString *username = arguments[@"username"];
    NSString *password = arguments[@"password"];
    EMError *error = [[EMClient sharedClient] loginWithUsername:username password:password];
    if (error) {
        result([FlutterError errorWithCode:[NSString stringWithFormat:@"%ld", (long)error.code] message:error.errorDescription details:nil]);
    } else {
        result(@(YES));
    }
}

- (void)loginWithTokenMethodWithCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSDictionary *args = call.arguments;
    NSDictionary *arguments = args[@"args"];

    NSString *username = arguments[@"username"];
    NSString *token = arguments[@"token"];
    EMError *error = [[EMClient sharedClient] loginWithUsername:username token:token];
    if (error) {
        result([FlutterError errorWithCode:[NSString stringWithFormat:@"%ld", (long)error.code] message:error.errorDescription details:nil]);
    } else {
        result(@(true));
    }
}

- (void)isLoginMethodWithCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    BOOL isLoggedInBefore = [HDClient sharedClient].isLoggedInBefore;
    result(@(isLoggedInBefore));
}

- (void)logoutMethodWithCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    EMError *error = [[EMClient sharedClient] logout:YES];
    if (error) {
        result([FlutterError errorWithCode:[NSString stringWithFormat:@"%ld", (long)error.code] message:error.errorDescription details:nil]);
    } else {
        result(@(true));
    }
}

- (void)loadMessagesWithCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSDictionary *args = call.arguments;
    NSDictionary *arguments = args[@"args"];
    
    NSString *aMessageId = arguments[@"startMsgId"] ?: @"";
    NSString *serviceNumber = arguments[@"to"];
    int count = [arguments[@"pageSize"] intValue] ?: 20;
    
    HDConversation *conversation = [[HDClient sharedClient].chatManager getConversation:serviceNumber];
    [conversation loadMessagesStartFromId:aMessageId
                                    count:count
                          searchDirection:HDMessageSearchDirectionUp
                               completion:^(NSArray<HDMessage *> *aMessages, HDError *aError) {
        if (aError) {
            result(aError.errorDescription);
        } else if (aMessages && aMessages.count > 0) {
            result([MessageManage messagesToListMapWithMessages:aMessages]);
        }
    }];
}


- (void)getAllMessageWithCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSDictionary *args = [call arguments];
    NSDictionary *arguments = args[@"args"];
    NSString *serviceNumber = arguments[@"to"];
  
    HDConversation *conversation = [[HDClient sharedClient].chatManager getConversation:serviceNumber];
    [conversation loadMessagesStartFromId:nil
                                    count:20
                          searchDirection:HDMessageSearchDirectionUp
                               completion:^(NSArray<HDMessage *> *aMessages, HDError *aError) {
        if (aError) {
            // 处理错误
            result(aError.errorDescription);
        } else if (aMessages && aMessages.count > 0) {
            // 获取到消息 messages
            result([MessageManage messagesToListMapWithMessages:aMessages]);
        }
    }];
}

- (void)unreadMessageCountWithCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSDictionary *args = [call arguments];
    NSDictionary *arguments = args[@"args"];
    NSString *serviceNumber = arguments[@"to"];
  
    HDConversation *conversation = [[HDClient sharedClient].chatManager getConversation:serviceNumber];
    int unreadCount = conversation.unreadMessagesCount;
    result(@(unreadCount));
}

- (void)markAllMessageAsReadWithCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSDictionary *args = [call arguments];
    NSDictionary *arguments = args[@"args"];
    NSString *serviceNumber = arguments[@"to"];
  
    HDConversation *conversation = [[HDClient sharedClient].chatManager getConversation:serviceNumber];
    [conversation markAllMessagesAsRead:nil];
}


- (void)sendEvalMessageWithCall:(FlutterMethodCall*)call result:(FlutterResult)result {
    NSDictionary *args = [call arguments];
    NSDictionary *arguments = args[@"args"];
    NSString *serviceNumber = arguments[@"to"];
    NSString *msgId = arguments[@"msgId"];
    NSString *degree_tags = arguments[@"degree_tags"];
    NSString *degree_id = arguments[@"degree_id"];

    ///获取会话
    HDConversation *conversation = [[HDClient sharedClient].chatManager getConversation:serviceNumber];

    ///根据msgID获取评价消息
    HDMessage *pMessage = [conversation loadMessageWithId:msgId error:nil];

    //创建空的文本消息
    HDMessage *message = [HDMessage createTxtSendMessageWithContent:@"" to:serviceNumber];

    //创建HDControlMessage对象
    HDControlMessage *hCtrl = [[HDControlMessage alloc] init];
    //设置ControlType
    ControlType *type = [[ControlType alloc] initWithValue:@"enquiry"];
    hCtrl.type = type;

    ControlArguments *ags = [[ControlArguments alloc] init];
    //设置sessionId
    NSDictionary *extDict = pMessage.ext;
    if (extDict[@"weichat"] != nil) {
        NSDictionary *weichatDict = extDict[@"weichat"];
        if (weichatDict[@"service_session"] != nil) {
            NSDictionary *serviceSessionDict = weichatDict[@"service_session"];
            ags.sessionId = serviceSessionDict[@"serviceSessionId"];
        }
    }

    //ags.evaluateWay = @"agent";
    ags.detail = [self getDetailWithId:degree_tags];
    ags.summary = [self getScoreWithId:degree_id];
    ///设置arguments
    hCtrl.arguments = ags;

    message.ext = extDict;
    //message添加hCtrl
    [message addCompositeContent:hCtrl];
    
    
    
    [[HDClient sharedClient].chatManager sendMessage:message progress:nil completion:^(HDMessage *aMessage, HDError *aError) {
        NSLog(@"%@", aError);
        if (aError != nil) {
            // 处理错误
            NSLog(@"%@", aError.errorDescription);
            result([NSNumber numberWithBool:NO]);
        } else if (aMessage != nil) {
            // 获取到消息 messages
            result([NSNumber numberWithBool:YES]);
        }
    }];
}

- (NSString *)getScoreWithId:(NSString *)id {
    if ([id isEqualToString:@"357115"]) {
        return @"5";
    } else if ([id isEqualToString:@"357116"]) {
        return @"4";
    } else if ([id isEqualToString:@"357117"]) {
        return @"3";
    } else if ([id isEqualToString:@"357118"]) {
        return @"2";
    } else if ([id isEqualToString:@"357119"]) {
        return @"1";
    } else {
        return @"";
    }
}

- (NSString *)getDetailWithId:(NSString *)id {
    if ([id isEqualToString:@"391115"]) {
        return @"已解决";
    } else if ([id isEqualToString:@"391117"]) {
        return @"已解决";
    } else if ([id isEqualToString:@"391119"]) {
        return @"已解决";
    } else if ([id isEqualToString:@"391121"]) {
        return @"已解决";
    } else if ([id isEqualToString:@"391123"]) {
        return @"已解决";
    } else if ([id isEqualToString:@"391116"]) {
        return @"未解决";
    } else if ([id isEqualToString:@"391118"]) {
        return @"未解决";
    } else if ([id isEqualToString:@"391120"]) {
        return @"未解决";
    } else if ([id isEqualToString:@"391122"]) {
        return @"未解决";
    } else if ([id isEqualToString:@"391124"]) {
        return @"未解决";
    } else {
        return @"";
    }
}


- (void)sendMessageWithCall:(FlutterMethodCall *)call result:(FlutterResult)result {
    NSDictionary *args = (NSDictionary *)call.arguments;
    NSDictionary *arguments = [args objectForKey:@"args"];
    NSString *type = [arguments objectForKey:@"type"];
    
    // 文字消息
    if ([type isEqualToString:@"text"]) {
        [self sendTextMeesageWithArguments:arguments result:result];
    }
    // 图片消息
    else if ([type isEqualToString:@"image"]) {
        [self sendImageMeesageWithArguments:arguments result:result];
    }
    // 视频消息
    else if ([type isEqualToString:@"video"]) {
        [self sendVideoMeesageWithArguments:arguments result:result];
    }
    // 语音消息
    else if ([type isEqualToString:@"voice"]) {
        [self sendVoiceMeesageWithArguments:arguments result:result];
    }
    // 文件消息
    else if ([type isEqualToString:@"file"]) {
        [self sendFileMeesageWithArguments:arguments result:result];
    }
    
    else if ([type isEqualToString:@"custom"]) {
          result(@"未实现");
    }
    
    else if ([type isEqualToString:@"cmd"]) {
         result(@"未实现");
    }
    
    else if ([type isEqualToString:@"location"]) {
        result(@"未实现");
    }
  }
         



- (void)sendTextMeesageWithArguments:(NSDictionary *)arguments result:(FlutterResult)result {
    NSString *text = @"";
    if ([arguments objectForKey:@"content"]) {
        text = [arguments objectForKey:@"content"];
    }
    NSString *toUser = [arguments objectForKey:@"to"];
    HDMessage *message;
    NSString *extType = @"";
    if ([arguments objectForKey:@"extType"]) {
        extType = [arguments objectForKey:@"extType"];
    }
    
    if ([extType isEqualToString:@"VisitorMsg"]) {
        // 发送带访客属性的消息
        message = [HDMessage createTxtSendMessageWithContent:@"" to:toUser];
        HDVisitorInfo *visitor = [[HDVisitorInfo alloc] init];
        visitor.qq = [arguments objectForKey:@"visitor_qq"];
        visitor.companyName = [arguments objectForKey:@"visitor_companyName"];
        visitor.nickName = [arguments objectForKey:@"visitor_nickName"];
        visitor.email = [arguments objectForKey:@"visitor_email"];
        visitor.desc = [arguments objectForKey:@"visitor_description"];
        visitor.phone = [arguments objectForKey:@"visitor_phone"];
        visitor.name = [arguments objectForKey:@"visitor_name"];
        [message addContent:visitor];
    } else if ([extType isEqualToString:@"TrackMsg"]) {
        // 发送轨迹消息
        message = [HDMessage createTxtSendMessageWithContent:@"" to:toUser];
        HDVisitorTrack *vst = [[HDVisitorTrack alloc] init];
        vst.title = [arguments objectForKey:@"track_title"];
        vst.price = [arguments objectForKey:@"track_price"];
        vst.desc = [arguments objectForKey:@"track_desc"];
        vst.imageUrl = [arguments objectForKey:@"track_imageUrl"];
        vst.itemUrl = [arguments objectForKey:@"track_itemUrl"];
        [message addContent:vst];
    } else if ([extType isEqualToString:@"orderMsg"]) {
        // 发送订单消息
        message = [HDMessage createTxtSendMessageWithContent:@"" to:toUser];
        HDOrderInfo *ord = [[HDOrderInfo alloc] init];
        ord.title = [arguments objectForKey:@"order_title"];
        ord.orderTitle = [arguments objectForKey:@"order_orderTitle"];
        ord.price = [arguments objectForKey:@"order_price"];
        ord.desc = [arguments objectForKey:@"order_desc"];
        ord.imageUrl = [arguments objectForKey:@"order_imageUrl"];
        ord.itemUrl = [arguments objectForKey:@"order_itemUrl"];
        [message addContent:ord];
    } else {
        // 文本消息
        message = [HDMessage createTxtSendMessageWithContent:text to:toUser];
    }
    
    [[HDClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
        // 发送消息进度
        NSLog(@"%d", progress);
    } completion:^(HDMessage *aMessages, HDError *aError) {
        // 发送消息完成，aError为空则为发送成功
        NSLog(@"%@", aError);
        if (aError) {
            // 处理错误
            result(aError.errorDescription);
        } else if (aMessages) {
            // 获取到消息 messages
            NSMutableArray *msgs = [[NSMutableArray alloc]initWithObjects:aMessages, nil];
            result([MessageManage messagesToListMapWithMessages:msgs]);
        }
    }];
}


- (void)sendImageMeesageWithArguments:(NSDictionary *)arguments result:(FlutterResult)result {
    NSString *filePath = [arguments objectForKey:@"filePath"];
    NSString *toUser = [arguments objectForKey:@"to"];
    UIImage *image = [UIImage imageNamed:filePath];
    HDMessage *message = [HDMessage createImageSendMessageWithImage:image displayName:[self currentTimeString] to:toUser];
  
    
    [[HDClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
            // 发送消息进度 Image
            NSLog(@"%d", progress);
        } completion:^(HDMessage *aMessage, HDError *aError) {
            // 发送消息完成，aError为空则为发送成功
            NSLog(@"%@", aError);
            if (aError) {
                // 处理错误
                result(aError.errorDescription);
            } else if (aMessage) {
                // 获取到消息 messages
                NSMutableArray *msgs = [[NSMutableArray alloc]initWithObjects:aMessage, nil];
                result([MessageManage messagesToListMapWithMessages:msgs]);
            }
        }];
}

- (void)sendVideoMeesageWithArguments:(NSDictionary *)arguments result:(FlutterResult)result {
    NSString *filePath = [arguments objectForKey:@"filePath"];
    NSString *toUser = [arguments objectForKey:@"to"];
    HDMessage *message = [HDMessage createVideoSendMessageWithLocalPath:filePath displayName:[self currentTimeString] to:toUser];
    [[HDClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
        // 发送消息进度 Image
        NSLog(@"%d", progress);
    } completion:^(HDMessage *aMessage, HDError *aError) {
        // 发送消息完成，aError为空则为发送成功
        NSLog(@"%@", aError);
        if (aError) {
            // 处理错误
            result(aError.errorDescription);
        } else if (aMessage) {
            // 获取到消息 messages
//            result([MessageManage messageToMapWithMessage:message]);
        }
    }];
}


- (void)sendVoiceMeesageWithArguments:(NSDictionary *)arguments result:(FlutterResult)result {
    NSString *filePath = [arguments objectForKey:@"filePath"];
    NSString *toUser = [arguments objectForKey:@"to"];
    NSString *length = [arguments objectForKey:@"length"];
    HDMessage *message = [HDMessage createVoiceSendMessageWithLocalPath:filePath duration:[length intValue] to:toUser];
    
    

    [[HDClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
        // 发送消息进度 Image
        NSLog(@"%d", progress);
    } completion:^(HDMessage *aMessage, HDError *aError) {
        // 发送消息完成，aError为空则为发送成功
        NSLog(@"%@", aError);
        if (aError) {
            // 处理错误
            result(aError.errorDescription);
        } else if (aMessage) {
            // 获取到消息 messages
            NSMutableArray *msgs = [[NSMutableArray alloc]initWithObjects:aMessage, nil];
            result([MessageManage messagesToListMapWithMessages:msgs]);
        }
    }];
        
}

- (void)sendFileMeesageWithArguments:(NSDictionary *)arguments result:(FlutterResult)result {
    NSString *filePath = [arguments objectForKey:@"filePath"];
    NSString *toUser = [arguments objectForKey:@"to"];
    HDMessage *message = [HDMessage createFileSendMessageWithLocalPath:filePath to:toUser];
    [[HDClient sharedClient].chatManager sendMessage:message progress:^(int progress) {
            
    } completion:^(HDMessage *aMessage, HDError *aError) {
        // 发送消息完成，aError为空则为发送成功
        NSLog(@"%@", aError);
        if (aError) {
            // 处理错误
            result(aError.errorDescription);
        } else if (aMessage) {
            // 获取到消息 messages
            NSMutableArray *msgs = [[NSMutableArray alloc]initWithObjects:aMessage, nil];
            result([MessageManage messagesToListMapWithMessages:msgs]);
        }
    }];
}

- (NSString *)currentTimeString {
    NSTimeInterval timestamp = [[NSDate date] timeIntervalSince1970];
    NSString *timestampString = [NSString stringWithFormat:@"%.0f", timestamp];
    return timestampString;
}



@end
